import builtins
from hzk import FontLib, FontLibHeader
from machine import I2C, Pin
import utime
from drivers.ssd1306 import SSD1306_I2C
import framebuf


oled = None
fontlib = None
font_file = 'fonts/SIMYOU_U24.bin'

def timed_function(f, *args, **kwargs):
	myname = str(f).split(' ')[1]

	def new_func(*args, **kwargs):
		t = utime.ticks_us()
		result = f(*args, **kwargs)
		delta = utime.ticks_diff(utime.ticks_us(), t)
		print('Function {} Time = {:6.3f}ms'.format(myname, delta/1000))
		return result
	return new_func

@timed_function
def get_characters(chars):
	global fontlib
	buffer_list = fontlib.get_characters(chars)
	return buffer_list

@timed_function
def get_fontlib():
	fontlib = FontLib(font_file)

	assert fontlib.encoding_flag != FontLibHeader.ENCODING_MBCS,\
		Exception('MicroPython only support Unicode fontlib')

	fontlib.info()
	return fontlib

@timed_function
def init_oled():
	global oled
	i2c = I2C(0, scl=Pin(18), sda=Pin(19))
	slave_list = i2c.scan()

	if slave_list:
		print('slave id: {}'.format(slave_list[0]))
		oled = SSD1306_I2C(128, 64, i2c)

		oled.fill(0)
		oled.show()

def oled_show(buffer, width, height, x, y):
	global oled
	fb = framebuf.FrameBuffer(bytearray(buffer), width, height, framebuf.MONO_HLSB)
	oled.blit(fb, x, y)
	oled.show()

def main():
	global fontlib, oled

	chars = '使用开发板进行信标定位功能测试'
	init_oled()
	fontlib = get_fontlib()
	buffer_list = get_characters(chars)
	x = y = 0
	width = height = fontlib.font_height

	def get_buffer(char):
		for buffer in buffer_list:
			if buffer[0] == ord(char):
				return buffer[2]

	for char in chars:
		buffer = get_buffer(char)

		if x > ((128 // width - 1) * width):
			x = 0
			y += height

		oled_show(buffer, width, height, x, y)
		x += width

	utime.sleep(5)

	for _ in range(20):
		oled.scroll(0, -1)
		oled.show()
		utime.sleep(0.1)


if __name__ == '__main__':
	main()
